#include "stdafx.h"
#include "LogInitializer.h"
#include "Log.h"
#include "LoggerImp.h"
#include "LoggerThreadSafe.h"
#include "LoggerAsync.h"
#include "LogTargetConsole.h"
#include "LogTargetFile.h"
#include "Config/Properties.h"

namespace woe
{

	LogInitializer::LogInitializer()
	{
		Logger* logger = new LoggerImp;

		logger->registerTarget(new LogTargetConsole, 0, LLB_ALL);

		Logger::instance(logger);
	}

	LogInitializer::LogInitializer(bool to_console, bool to_file, const string& file_name /* = */ )
	{
		Logger* logger = new LoggerImp;
		Logger::instance(logger);

		if (to_console)
		{
			logger->registerTarget(new LogTargetConsole, 0, LLB_ALL);
		}

		if (to_file)
		{
			logger->registerTarget(new LogTargetFile(file_name), 0, LLB_ALL);
		}
	}

	LogInitializer::LogInitializer(Properties& props)
	{
		initialize(props);
	}



	LogInitializer::LogInitializer(const string& config_file_name)
	{
		woe::Properties props;
		if (props.init(config_file_name))
		{
			initialize(props);
		}
		else
		{
			std::cout<<"Failed to initialize logger!, Invalid properties file!"<<endl;
			Logger* logger = new LoggerImp;
			Logger::instance(logger);
		}
	}

	void LogInitializer::initialize(Properties& props)
	{
		//
		//	Initialize the logger system from log file
		Logger* logger = NULL;
			
		int logger_type = LGT_Simple;
		if (props.parse("logger", logger_type))
		{
			if (logger_type== LGT_ThreadSafe)
			{
				logger = new LoggerThreadSafe;
			}
			else if(logger_type== LGT_Async)
			{
				logger = new LoggerAsync;
			}
		}

		if (logger==NULL)
		{
			logger = new LoggerImp;
		}

		Logger::instance(logger);

		short level = 0;
		if (props.parse(TS("level"), level))
		{
			if (level==0)
			{
				string level_name;
				if(props.parse(TS("level"), level_name))
				{
					level = LogLevelUtil::getLogLevel(level_name);
					logger->setLogLevel(level);
				}
			}
		}

		bool bv = true;
		if (props.parse(TS("to_console"), bv) && bv)
		{
			if (!props.parse(TS("to_console_level"), level))
			{
				level = 0;
			}

			logger->registerTarget(new LogTargetConsole, level, LLB_ALL);
		}

		if (props.parse(TS("to_file"), bv) && bv)
		{
			if (!props.parse(TS("to_file_level"), level))
			{
				level = 0;
			}

			string file_name;

			if (props.parse(TS("to_file_name"), file_name))
			{
				logger->registerTarget(new LogTargetFile(file_name), level, LLB_ALL);
			}
		}
	}
}